﻿// 2_7_string_2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include<string>
#include<assert.h>
using namespace std;

void test_string()
{
    string s = "how are you";
    //insert 函数   效率太低下，插入字符串的时候，会挪动后面的数据，不常用
    s.insert(11, " i am fine");
    cout << s << endl;
    s.insert(5, "1111111");
    cout << s << endl;

    //erase函数
    s.erase(5, 7);
    cout << s << endl;
    s.erase(11);  //如果不指定长度的话，直接删除到末尾，删除之后，capacity不一定改变
    cout << s << endl;


    //assign函数
    string s2(s);
    s2.assign("and you ?");
    cout << s2 << endl;
    s.assign("ba ga ya lu", 3,8); //指定截取字符串的位置重新s字符串
    cout << s << endl;
    string s3 = "I am the only";
    s.assign(s3.begin(), s3.end());
    cout << s << endl;
}

void test_string2()
{
    string s = "i love you baby";
    cout << s << endl;
    //size_t pos = s.find(' ');
    //while (pos != string::npos)
    //{
    //    s.replace(pos, 1, "%20");  //效率过于低下
    //    pos = s.find(' ', pos + 3);
    //}
    
    //一个快速替换你想要的字符串 用空间换时间
    string s2;
    size_t _size = s.size();
    s2.reserve(_size + 1);  //如果知道扩容多大，就直接reserve到那么大

    for (auto ch : s)
    {
        if (ch == ' ')
        {
            s2 += "%20";
        }
        else
        {
            s2 += ch;
        }
    }
    cout << s2 << endl;

}

void test_string3()
{
    string s("1.txt");
    FILE* pf=fopen(s.c_str(),"r");   //s.c_str()一般是用作c语言和c++语言交互上面
    assert(pf);
    char ch = fgetc(pf);
    while (ch != EOF)
    {
        cout << ch;
        ch = fgetc(pf);
    }
    fclose(pf);
    


    cout <<endl<< s.data() << endl;  //data()函数就是返回字符串的内容
}

void test_string4()
{
    //string s("rose rose i love you");
    //size_t pos = s.find("love",0,2);
    //size_t rpos = s.rfind('u');    //倒着查找
    //cout << pos << endl << rpos << endl;

    //查找string里面的最后一个单词,就可以使用倒着找

    string s1 = "you are bull shit";
    size_t rpos = s1.rfind(' '); //这个结束的重点也是string::npos
    for (rpos; rpos < s1.size(); rpos++)
    {
        cout << s1[rpos];
    }
    cout << endl;
    //也可以通过这个寻找文件的后缀名
    string s2 = "a.out.tar.zip";
    size_t rpos2 = s2.rfind('.');
    for (rpos2; rpos2 < s2.size(); rpos2++)
    {
        cout << s2[rpos2];
    }
    cout << endl;


    std::string str("Please, replace the vowels in this sentence by asterisks.");
    std::size_t found = str.find_first_of("aeiou");
    while (found != std::string::npos)
    {
        str[found] = '*';
        found = str.find_first_of("aeiou", found + 1);
    }

    std::cout << str << '\n';
}


void test_string5()
{
    string s1("hello world");
    cout<<s1.substr(0, 5)<<endl;    //截取指定长度的字符串返回

    //
    string str1 = "1111";
    const char* p = "2222";
    str1 == p;
    p == str1;
}
void test_string5()
{
    string line;
    // 不要使用cin>>line,因为会它遇到空格就结束了
    // while(cin>>line)
    getline(cin, line);
    size_t pos = line.rfind(' ');
    cout << line.size() - pos - 1 << endl;
}

int main()
{
    test_string5();
    return 0;
}

